/**
 * Copyright (c) 2012, Brent Mucci, Ken Anderson
 * All rights reserved.
 * 
 * Redistribution and use in source and binary forms, with or without modification, 
 * are permitted provided that the following conditions are met:
 * 
 * 1. Redistributions of source code must retain the above copyright notice, 
 *    this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright notice, 
 *    this list of conditions and the following disclaimer in the documentation 
 *    and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" 
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE 
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE 
 * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR 
 * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES 
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; 
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON 
 * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, 
 * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 **/

#include "mcl_nal.hpp"
using namespace mcl;

#define RBSP_INITIAL_SIZE 4080


NAL::NAL() : m_rbsp_bytes(RBSP_INITIAL_SIZE)
{
}

NAL::~NAL()
{
}

bool NAL::parse(BitstreamBuffer &bitstream, const int numBytes)
{
	m_numBytesInNALunit = numBytes;
	m_rbsp_bytes.clear();
	m_rbsp_bytes.resize(numBytes-1);

	m_forbidden_zero_bit = bitstream.read_bits(1);
	m_nal_ref_idc = bitstream.read_bits(2);
	m_nal_unit_type = bitstream.read_bits(5);

	unsigned int nalUnitHeaderBytes = 1;

	if(m_nal_unit_type == 14 || m_nal_unit_type == 20)
	{
		m_svc_extension_flag = bitstream.read_bits(1);
		if(m_svc_extension_flag)
		{
			// SVC not supported.
		}
		else
		{
			m_mvc_header.parse(bitstream);
		}
		nalUnitHeaderBytes += 3;
	}
	for(unsigned int i = nalUnitHeaderBytes; i < m_numBytesInNALunit; i++)
	{
		if(i + 2 < m_numBytesInNALunit && bitstream.next_bits(24) == 0x3)
		{
			// NumBytesInRBSP is not necessary since the list has a .size() for the number of RBSP bytes present.
			m_rbsp_bytes.push_back(bitstream.read_bits(8));
			m_rbsp_bytes.push_back(bitstream.read_bits(8));
			i += 2;
			bitstream.read_bits(8); // emulation_prevention_three_byte, this is to be discarded
		}
		else
		{
			m_rbsp_bytes.push_back(bitstream.read_bits(8));
		}
	}
	return true;
}